package cn.wenhaha.job;

import org.quartz.*;

import java.util.Map;

/**
 * 动态创建和删除任务
 * --------
 *
 * @author ：wyndem
 * @Date ：Created in 2022-01-28 16:10
 */
public class ScheduleDynamicUtil {

    protected  static  Scheduler scheduler;


    /**
     * @Author: Wyndem
     * @Description: 添加任务
     * @DateTime: 2022-01-28 16:27
     */
    public static void addJob(DynamicJob job){
        WynJobBean jobBean = job.getJob();
        if (jobBean==null){
            return;
        }
        String cron = job.getCron();
        if (cron==null || cron.isEmpty()){
            throw new RuntimeException("cron表达式不能为空");
        }
        long l = job.getJobId();
        if (l==0){
            l=job.hashCode();
        }

        WynJobInfo wynJobInfo = new WynJobInfo().setJob(jobBean).setJobId(l)
                .setJobGroup(job.getJobGroup()).setCronExpression(cron);

        try {
            createScheduleJob(wynJobInfo,job.getData());
        } catch (SchedulerException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    public static Trigger.TriggerState  statusJob(Long jobId, String jobGroup) throws SchedulerException {
        TriggerKey triggerKey = ScheduleUtils.getTriggerKey(jobId, jobGroup);
        return scheduler.getTriggerState(triggerKey);
    }


    /**
     * @Author: Wyndem
     * @Description: 删除任务
     * @DateTime: 2022-01-28 16:27
     */
    public static void  deleteJob(Long jobId, String jobGroup){

        try {
            // 判断是否存在
            if (scheduler.checkExists(ScheduleUtils.getJobKey(jobId, jobGroup)))
            {
                TriggerKey triggerKey = ScheduleUtils.getTriggerKey(jobId, jobGroup);
                // 防止创建时存在数据问题 先移除，然后在执行创建操作
                scheduler.pauseTrigger(triggerKey);// 停止触发器
                scheduler.unscheduleJob(triggerKey);// 移除触发器
               scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
            }

        } catch (SchedulerException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    private static void createScheduleJob(WynJobInfo  job, Map<String, Object> data) throws SchedulerException {

        // 构建job信息
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        JobDetail jobDetail = JobBuilder.newJob(job.getJob().getClass()).withIdentity(ScheduleUtils.getJobKey(jobId, jobGroup)).build();

        // 表达式调度构建器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
        cronScheduleBuilder=cronScheduleBuilder.withMisfireHandlingInstructionDoNothing();

        // 放入参数，运行时的方法可以获取
        jobDetail.getJobDataMap().putAll(data);

        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(ScheduleUtils.getTriggerKey(jobId, jobGroup))
                .withSchedule(cronScheduleBuilder).build();

        // 放入参数，运行时的方法可以获取
//        jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job);
        deleteJob(jobId,jobGroup);

        scheduler.scheduleJob(jobDetail, trigger);

    }
}
